<?php
if (isset($_GET['sessid'])) { define('SE_SESSION_RESUME', TRUE); $session_id = $_GET['sessid']; } elseif (isset($_POST['sessid'])) { define('SE_SESSION_RESUME', TRUE); $session_id = $_POST['sessid']; }

chdir('../../../../');
include "header.php";

if (isset($_GET['plugin'])) { $plugin = $_GET['plugin']; } elseif (isset($_POST['plugin'])) { $plugin = $_POST['plugin']; }
if (isset($_GET['id'])) { $plugin_user_id = $_GET['id']; } elseif (isset($_POST['id'])) { $plugin_user_id = $_POST['id']; }
if (isset($_GET['album'])) { $plugin_album = (int)$_GET['album']; } elseif (isset($_POST['album'])) { $plugin_album = (int)$_POST['album']; } else { $plugin_album = 0; }
if (isset($_GET['path'])) { $plugin_path = preg_replace("#[^A-Za-z0-9:\_\-/]#", "", $_GET['path']); } elseif (isset($_POST['path'])) { $plugin_pth = preg_replace("#[^A-Za-z0-9:\_\-/]#", "", $_POST['path']); } else { $plugin_path = ""; }

$msep->setPlugin($plugin, false);
$plugin = $msep->gets('plugin');

if (empty($plugin))
{
      HandleError("Upload failed.");
      exit(0);
}

if (!$user->user_exists && !$msep->get('database')->num_rows($msep->get('database')->query("SELECT user_id FROM se_users WHERE user_id = '{$plugin_user_id}'")))
{
      HandleError("Unauthorized upload.");
      exit(0);
}

if (empty($plugin_path))
{
      $tmp_dir = "./uploads_{$plugin}/tmp/";
}
else
{
      $tmp_dir = $plugin_path;
}

if ($plugin_user_id > 0)
{
      $user->user_info["user_id"] = $plugin_user_id;
      $tmp_dir = $msep->get('misc')->user_dir($plugin_user_id);

      $path_array = explode("/", $tmp_dir);
      array_pop($path_array);
      array_pop($path_array);
      $subdir = implode("/", $path_array)."/";

      if(!is_dir($subdir))
      {
            mkdir($subdir, 0777);
            chmod($subdir, 0777);
            $handle = fopen($subdir."index.php", 'x+');
            fclose($handle);
      }

      if(!is_dir($tmp_dir))
      {
            mkdir($tmp_dir, 0777);
            chmod($tmp_dir, 0777);
            $handle = fopen($tmp_dir."/index.php", 'x+');
            fclose($handle);
      }
}

$POST_MAX_SIZE = ini_get('post_max_size');
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE)
{
      header("HTTP/1.1 500 Internal Server Error");
      echo "POST exceeded maximum allowed size.";
      exit(0);
}

$upload_name = "the_file";
$max_file_size_in_bytes = 2147483647;

$MAX_FILENAME_LENGTH = 260;
$file_name = "";
$uploadErrors = array(0 => "There is no error, the file uploaded with success",
                      1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
                      2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                      3 => "The uploaded file was only partially uploaded",
                      4 => "No file was uploaded",
                      6 => "Missing a temporary folder"
);

if (!isset($_FILES[$upload_name]))
{
      HandleError("No upload found in \$_FILES for " . $upload_name);
      exit(0);
}
elseif (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0)
{
      HandleError($uploadErrors[$_FILES[$upload_name]["error"]]);
      exit(0);
}
elseif (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"]))
{
      HandleError("Upload failed is_uploaded_file test.");
      exit(0);
}
elseif (!isset($_FILES[$upload_name]['name']))
{
      HandleError("File has no name.");
      exit(0);
}

$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);

if (!$file_size || $file_size > $max_file_size_in_bytes)
{
      HandleError("File exceeds the maximum allowed size");
      exit(0);
}

if ($file_size <= 0)
{
      HandleError("File size outside allowed lower bound");
      exit(0);
}

$ranNum = rand(100,9999).'-'.Rand(10000,999999);
$file_name = md5($ranNum);

if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH)
{
      HandleError("Invalid file name");
      exit(0);
}

if (file_exists($tmp_dir.$file_name))
{
      HandleError("File with this name already exists");
      exit(0);
}

if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $tmp_dir.$file_name))
{
      HandleError("File could not be saved.");
      exit(0);
}

if ($plugin_album == 0)
{
      echo $file_name;
      exit(0);
}
else
{
      $msep->get('database')->query("INSERT INTO se_{$plugin}s ({$plugin}_user_id, {$plugin}_datecreated, {$plugin}_path, {$plugin}_album_id) VALUES ('{$user->user_info['user_id']}', '".time()."', '{$file_name}', '{$plugin_album}')");
      $insert_id = $msep->get('database')->insert_id();

      $msep->get('database')->query("UPDATE se_{$plugin}albums SET album_dateupdated = '".time()."' WHERE album_id = '{$plugin_album}'");

      if (file_exists("{$plugin}_process.php"))
      {
              include "{$plugin}_process.php";
      }

      echo $file_name;
      exit(0);
}

function HandleError($message)
{
      echo $message;
}
?>